#include "log.hpp"
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

using func_t = std::function<std::string(const std::string&)>;
//typedef std::function<std::string(const std::string&)> func_t;

enum{
    SOCKET_ERR = 1,
    BIND_ERR
};
Log log;
const std::string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;
const int buffsize = 4096;

class udp_server{
public:
    udp_server(const uint16_t port = defaultport, const std::string &ip = defaultip) 
        :sockfd_(0), ip_(ip), port_(port), isrunning_(false)
    {}
    void Init()
    {
        // 1. 创建udp socket
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);  //PF_INET
        if (sockfd_ < 0)
        {
            log(Fatal, "socket create error, sockfd: %d", sockfd_);
            exit(1);
        }
        log(Info, "socket create success, sockfd: %d", sockfd_);

        // 2. 初始化sockaddr_in
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);  // 将端口号转为网络字节序列
        //local.sin_addr.s_addr = inet_addr(ip_.c_str());  
        // 用于ssh登录的ip地址是虚拟化过的,云服务器不支持绑定虚拟化的公网IP。
        // 如果需要用绑定指定ip的话,请用"ifconfig"命令查看到的网卡IP
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        // 1.string -> uint32_t   2. uint32_t -> 网络字节序列 

        // 3. bind
        if (bind(sockfd_, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            log(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }   
        log(Info, "bind success");
    }

    void Run(func_t func)
    {
        isrunning_ = true;
        char inbuffer[buffsize];
        inbuffer[0] = 0;
        while (isrunning_)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer)-1, 0, (struct sockaddr*)&client, &len);
            if (n < 0)
            {
                log(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = 0;  // '/0'
            std::string info = inbuffer;
            std::string echo_string = func(info);
            sendto(sockfd_, echo_string.c_str(), echo_string.size(), 0, (const sockaddr*)&client, len);         
        }
    }
    ~udp_server()
    {
        if (sockfd_ > 0) close(sockfd_);
    }
private:
    int sockfd_;      // 网络文件描述符
    std::string ip_;  // 地址(任意地址bind 0)
    uint16_t port_;   // 服务器进程的端口号
    bool isrunning_;
};